/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.shiro.config;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyts.infodb.path.InfodbConfiguration;
import com.hyts.infodb.shiro.bean.UserPO;
import com.hyts.infodb.shiro.bean.UserVO;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.hyts.infodb.config.StatusTypeEnum;

import org.springframework.web.client.RestTemplate;

/** 
 * @author LiBo/Alex
 * @version V1.0 
 */
//@Component
public class UserRealm extends AuthorizingRealm{
    
    /* 
     * @return
     * @see org.apache.shiro.realm.CachingRealm#getName()  
     * @exception
     */ 
    @Override
    public String getName() {
        return "infodb";
    }


    @Resource
    private RestTemplate restTemplate;


    @Resource
    InfodbConfiguration infodbConfiguration;

    /* (非 Javadoc)
     * @param principals
     * @return
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)  
     * @exception
     */ 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /* 
     * @param token
     * @return
     * @throws AuthenticationException
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)  
     * @exception
     */ 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        JSONObject userVOJSON = restTemplate.getForObject(infodbConfiguration.getUserAddress()+"user/get/"+userName,JSONObject.class);
        UserVO userVO = JSON.toJavaObject(userVOJSON, UserVO.class);
        if(userVO == null || userVO.getContent() == null) {
            //没找到帐号       
            throw new UnknownAccountException("用户名不存在");
        }else if(userVO.getTotalDataSize() > 1) {
            //账号不唯一
            throw new AccountException("账号数据异常，系统数据出现紊乱");
        }/*else if(String.valueOf(token.getCredentials()).equals(userVO.getContent().getEncryptPassword())){
            throw new AuthenticationException ("用户名或者密码错误！");
        }*/else if(userVO.getContent().getState() == 
                StatusTypeEnum.IS_LOCK.getValue().byteValue()){
            //账号被锁定
            throw new LockedAccountException("账号已被锁定！");
        }
        UserPO po = userVO.getContent();
        SimpleAuthenticationInfo authentication = 
                new SimpleAuthenticationInfo(po.getUserName(),
                        po.getEncryptPassword(),ByteSource.Util.bytes(po.getSalt()),getName());
        return authentication;
    }

}
